package top.yj95.xiets.basic;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JToggleButton;
import javax.swing.WindowConstants;

/**
 * 文章《<a href="https://xiets.blog.csdn.net/article/details/74363501" target="_balnk">JavaSwing_2.5: JToggleButton（开关按钮）</a>》中的示例代码
 * @author 杨军
 * @since 2023-12-22
 */
public class CustomizeJToggleButonDemo {
    
    public static void main(String[] args) {
        JFrame frame = new JFrame("测试窗口");
        frame.setSize(250, 200);
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        
        
        JPanel panel = new JPanel();
        
        // 创建开关按钮
        JToggleButton toggleBtn = new JToggleButton();
        
        // 首先设置不绘制按钮边框
        toggleBtn.setBorderPainted(false);
        
        // 设置 选中（开） 和 未选中（关） 时显示的图片
        toggleBtn.setSelectedIcon(new ImageIcon(CustomizeJToggleButonDemo.class.getResource("/assets/images/jtoggle/toggle_on.png")));
        toggleBtn.setIcon(new ImageIcon(CustomizeJToggleButonDemo.class.getResource("/assets/images/jtoggle/toggle_off.png")));
        
        // 添加 toggleBtn 的状态被改变的监听
        toggleBtn.addChangeListener(e -> {
            JToggleButton btn = (JToggleButton) e.getSource();
            System.out.printf("%s 是否选中：%s\n", btn.getText(), btn.isSelected());
        });
        
        panel.add(toggleBtn);
        
        frame.setContentPane(panel);
        frame.setVisible(true);
    }
    
}
